<template>
  <div>
    <el-form ref="form" :model="form" :status-icon="true" :rules="regRule">
      <el-form-item prop="user_image">
        <el-row type="flex" justify="center">
          <h3 style="color: orangered">*请自行裁剪1寸照片并上传</h3>
        </el-row>
        <el-row type="flex" justify="center">
          <el-upload
            ref="upload"
            action="http://49.235.120.164:9000/users/1/"
            :http-request="patchData"
            class="avatar-uploader"
            :show-file-list="false"
            :on-change="eventOnUploadChange"
            :auto-upload="false"
            :data="form"
            :file-list="imageList"
            :limit="2"
          >
            <el-image style="width: 142px; height: 200px" :src="imageUrl" fit="fill">
              <div slot="error">
                <i class="el-icon-plus avatar-uploader-icon" />
              </div>
            </el-image>
          </el-upload>
        </el-row>
      </el-form-item>
      <el-divider />
      <el-form-item label="性别：" prop="gender" label-width="65px">
        <el-radio-group v-model="form.gender">
          <el-radio-button label="1">男</el-radio-button>
          <el-radio-button label="0">女</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="姓名：" prop="name" label-width="65px">
        <el-input v-model="form.name" placeholder="请输入你的姓名" />
      </el-form-item>

      <el-form-item label="籍贯：" prop="Id_address" label-width="65px">
        <el-input v-model="form.Id_address" placeholder="籍贯格式如：贵州省-贵阳市" />
      </el-form-item>

      <el-form-item label="身份证：" prop="id_card" label-width="80px">
        <el-input v-model="form.id_card" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="年龄：" prop="age" label-width="65px">
        <el-input v-model="form.age" placeholder="请输入你的年龄" />
      </el-form-item>

      <el-form-item label="毕业院校：" prop="school" label-width="95px">
        <el-input
          v-model="form.school"
          placeholder="请输入你的毕业院校"
        />
      </el-form-item>

      <el-form-item label="专业：" prop="major" label-width="65px">
        <el-input v-model="form.major" placeholder="请输入你的专业" />
      </el-form-item>

      <el-form-item label="联系电话：" prop="mobile" label-width="95px">
        <el-input v-model="form.mobile" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="电子邮箱：" prop="email" label-width="95px">
        <el-input
          v-model="form.email"
          placeholder="请输入正确的邮箱"
        />
      </el-form-item>
      <el-form-item label="出生日期：" prop="birthday" label-width="95px">
        <el-date-picker
          v-model="form.birthday"
          type="date"
          placeholder="选择你的出生日期"
          style="width: 100%"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item label="政治面貌：" prop="Political" label-width="95px">
        <el-select v-model="form.Political" placeholder="请选择你的政治面貌">
          <el-option label="群众" value="3" />
          <el-option label="共青团员" value="2" />
          <el-option label="中国共产党员" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="学历：" prop="education" label-width="65px">
        <el-select v-model="form.education" placeholder="请选择你的学历">
          <el-option label="初中及以下" value="初中及以下" />
          <el-option label="高中" value="高中" />
          <el-option label="大专" value="大专" />
          <el-option label="本科" value="本科" />
          <el-option label="硕士及以上" value="硕士及以上" />
        </el-select>
      </el-form-item>

      <el-form-item label="家庭住址：" prop="Home_address" label-width="95px">
        <el-input
          v-model="form.Home_address"
          type="textarea"
          placeholder="请输入你的家庭住址"
        />
      </el-form-item>
      <el-row type="flex" justify="between">
        <el-button icon="el-icon-takeaway-box" style="width: 30%;" @click="eventOnSave">保存</el-button>
        <el-button type="primary" icon="el-icon-check" style="width: 40%;" :loading="submitLoading" @click="eventOnSubmit">提交</el-button>
        <el-button type="danger" icon="el-icon-delete" style="width: 30%;" @click="eventOnClear">清空</el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script>

import { patchPersonInfo } from '@/api/user'
import {
  validateAge, validateEmail,
  validateEmpty,
  validateIdAddress,
  validateIdCard,
  validateName, validatePhone
} from '@/utils/validate-person-info'

export default {
  name: 'StudentBaseInfoRegister',
  data() {
    return {
      submitLoading: false,
      form: {
        name: '', // 姓名
        gender: '', // 性别
        id_card: '', // 身份证号
        Id_address: '',
        age: '', // 年龄
        birthday: '', // 出生日期
        Political: '',
        education: '',
        school: '', // 毕业院校
        major: '', // 专业
        mobile: '', // 电话
        email: '', // 电子邮校
        Home_address: ''
      },
      imageUrl: this.$store.getters.baseInfo.user_image,
      imageList: [],
      regRule: {
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        gender: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        id_card: [{ required: true, trigger: 'blur', validator: validateIdCard }],
        Id_address: [{ required: true, trigger: 'blur', validator: validateIdAddress }],
        age: [{ required: true, trigger: 'blur', validator: validateAge }],
        birthday: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        Political: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        education: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        school: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        major: [{ required: true, trigger: 'blur', validator: validateEmpty }],
        mobile: [{ required: true, trigger: 'blur', validator: validatePhone }],
        email: [{ required: true, trigger: 'blur', validator: validateEmail }],
        Home_address: [{ required: true, trigger: 'blur', validator: validateEmpty }]

      },
      apiHeaders: {
        'Authorization': `JWT ${this.$store.getters.token}`,
        'Content-Type': 'multipart/form-data'
      }
    }
  },
  mounted() {
    const formData = JSON.parse(sessionStorage.getItem('formData'))
    this.form = formData.form
    this.imageUrl = formData.imageUrl
    console.log(this.imageUrl)
    this.imageList = formData.imageList
  },
  methods: {
    createPatchData(file) {
      const formData = new FormData()
      if (file) {
        formData.append('user_image', file)
      }
      formData.append('name', this.form.name)
      formData.append('gender', this.form.gender)
      formData.append('id_card', this.form.id_card)
      formData.append('Id_address', this.form.Id_address)
      formData.append('age', this.form.age)
      formData.append('birthday', this.form.birthday)
      formData.append('education', this.form.education)
      formData.append('school', this.form.school)
      formData.append('major', this.form.major)
      formData.append('mobile', this.form.mobile)
      formData.append('email', this.form.email)
      formData.append('Home_address', this.form.Home_address)
      const formHeader = {
        'Authorization': `JWT ${this.$store.getters.token}`,
        'Content-Type': 'multipart/form-data'
      }
      patchPersonInfo(formData, formHeader).then(res => {
        this.submitLoading = false
        // console.log(res)
        this.$message({
          message: '上传成功!',
          type: 'success',
          duration: 5000
        })
        this.$refs.form.resetFields()
        this.imageUrl = ''
        this.imageList = []
        this.$emit('setClose', false)
      }).catch(() => {
        this.submitLoading = false
        this.$message({
          message: '上传失败, 请重新尝试!',
          type: 'warning',
          duration: 5000
        })
      })
    },
    patchData(e) {
      const file = e.file
      this.createPatchData(file)
    },
    eventOnSubmit() {
      this.submitLoading = true
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.imageList.length !== 0) {
            this.$refs.upload.submit()
          } else {
            if (this.imageUrl !== '') {
              this.createPatchData()
            } else {
              this.$message({
                message: '你还没有上传1寸照片',
                type: 'Error',
                duration: 3000
              })
            }
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    eventOnSave() {
      const formDataDict = {
        form: this.form,
        imageUrl: this.imageUrl,
        imageList: this.imageList
      }
      sessionStorage.setItem('formData', JSON.stringify(formDataDict))
      this.$message({
        type: 'success',
        message: '内容保存成功，刷新页面将会清空数据！',
        duration: 4000
      })
    },
    eventOnUploadChange(file) {
      const isJPG = file.raw.type === 'image/jpeg'
      const isPNG = file.raw.type === 'image/png'
      const isLt2M = file.raw.size / 1024 / 1024 < 2
      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      this.imageList = []
      this.imageList[0] = file
      this.imageUrl = URL.createObjectURL(file.raw)
      return true
    },
    eventOnClear() {
      this.$confirm('确定清空吗，保存的数据将会被清空！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'warning',
          message: '已经成功清空!'
        })
        this.$refs.form.resetFields()
        this.imageUrl = ''
        this.imageList = []
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消清空.'
        })
      })
    },
    clearAllData() {
      this.$refs.form.resetFields()
      this.imageUrl = ''
      this.imageList = []
    }
  }
}
</script>
<style>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 45px;
  color: #8c939d;
  width: 142px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}
.avatar {
  width: 142px;
  height: 200px;
  display: block;
}
</style>
